package top.withu.gaof.freehope.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import top.withu.gaof.freehope.constant.FileConstant;
import top.withu.gaof.freehope.dao.PhotoPathRespository;
import top.withu.gaof.freehope.model.PhotoPath;
import top.withu.gaof.freehope.res.FileRes;
import top.withu.gaof.freehope.service.FileService;

/**
 * @author Gaofan
 * @date 2018年12月25日 上午10:40:39
 * @describe
 */
@Service
public class FileServiceImpl implements FileService {

	@Autowired
	private FileConstant fileConstant;
	
	@Autowired
	private PhotoPathRespository repository;

	@Override
	public FileRes uploadFile(MultipartFile file,String type,String user) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		UploadManager uploadManager = new UploadManager(cfg);
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = null;
		FileRes fileRes = new FileRes();
		Auth auth = Auth.create(fileConstant.getAccessKey(), fileConstant.getSecretKey());
		String upToken = auth.uploadToken(fileConstant.getBucketTest());
		try {
			Response response = uploadManager.put(file.getBytes(), key, upToken);
			System.out.println("请求相应： " + response.bodyString());
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			fileRes.setFileName(putRet.key);
			fileRes.setViewUrl(fileConstant.getViewUrl() + "/" + putRet.key);
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				// ignore
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		PhotoPath path = new PhotoPath();
		path.setFilePath(fileRes.getViewUrl());
		path.setUser(user);
		path.setFileName(file.getOriginalFilename());
		path.setType(type);
		repository.save(path);
		return fileRes;

	}
}
